package com.tao.HouseRent.service;

import com.tao.HouseRent.domain.House;

/**
 * 定义House数组，保存House对象
 * 相应HouseView的调用
 * 完成对房屋信息的增删改查
 */
public class HouseService {

    private House[] houses; ;//定义House数组，保存House对象
    private int houseNums = 1;//记录当前有几个房屋信息
    private int idCounter = 1;//记录当前id增长到哪个值
    //构造器
    public HouseService(int size){
        houses = new House[size]; //创建数组大小
        houses[0] = new House(1,"jack","123","海淀区",1000,"未出租");
    }

    public House findById(int findId){
        for (int i = 0; i < houseNums; i++) {
            if(findId == houses[i].getId()){
                return houses[i];
            }
        }
        return null;
    }

    public boolean del(int delId){
        int index = -1;
        for (int i = 0; i < houseNums; i++) {
            if(delId == houses[i].getId()){
                index = i;
            }
        }
        if(index == -1){//说明delId不存在
            return false;
        }
        for (int i = index; i < houseNums - 1; i++) {
            houses[i] = houses[i+1];
        }
        houses[houseNums - 1] = null;
        houseNums--;//或者houses[--houseNums - 1] = null;
        return true;
    }
    public boolean add(House newHouse){
        //判断是否还可以继续添加
        if(houseNums >= houses.length){
            System.out.println("数组已满，不能再添加");
            return false;
        }
        //把newHouse保存到数组中
        houses[houseNums] = newHouse;
        houseNums++;//也可以写成houses[houseNums++] = newHouse;
        //ID自增长机制
        idCounter++;
        newHouse.setId(idCounter);
        return true;

    }
    //返回houses
    public House[] list(){
        return houses;
    }
}
